package com.ebupt.migu.music.login.controller;

import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.TokenUtils;
import com.ebupt.migu.music.login.service.TokenLogService;
import com.ebupt.migu.music.system.entity.AuthUser;
import com.ebupt.migu.music.system.service.AuthUserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

import static com.google.common.collect.Maps.newHashMapWithExpectedSize;

/**
 * 一键登录类
 *
 * @author zhuaoran
 */
@Slf4j
@RestController
public class CheckLoginController {

    /**
     * 这样使用，request每次进来都是Current Request
     */
    @Autowired
    HttpServletRequest request;

    @Autowired
    AuthUserService authUserService;

    @Autowired
    TokenLogService tokenLogService;

    /**
     * 是否允许token重复验证
     */
    @Value("${system.login.repeat}")
    private boolean isRepeat;

    /**
     * 跳转返回菜单menuID
     *
     * @param headers headers包含加密字符串
     * @return 返回登陆人信息
     */
    @PostMapping(value = "/checkLogin", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultObject checkLogin(@RequestHeader HttpHeaders headers) {
        String token = headers.getFirst("token");
        Map<String, Object> paramMap = newHashMapWithExpectedSize(2);
        paramMap.put("token", token);
        // 判断token是否为空
        if (StringUtils.isBlank(token)) {
            throw new MyException(StatusEnum.TOKEN_NULL, "token为空");
        }
        // 测试环境不启用
        if (isRepeat) {
            // 查询token是否已经被使用
            if (tokenLogService.queryByToken(paramMap) > 0) {
                throw new MyException(StatusEnum.TOKEN_INVALID, "token已作废");
            }
            tokenLogService.addTokenLog(paramMap);
        }
        ResultObject<Map<String, Object>> resultObject = new ResultObject<>();
        try {
            Claims claims = TokenUtils.parseJWT(token);
            paramMap.put("loginId", claims.getId());
            // 查询当前用户的基本信息
            List<AuthUser> userList = authUserService.queryAuthUser(paramMap);
            // 判断用户是否为空
            if (userList.isEmpty()) {
                throw new MyException(StatusEnum.NORIGHT, "该用户不存在");
            }
            Map<String, Object> map = newHashMapWithExpectedSize(1);
            map.put("user", userList.get(0));
            resultObject.setData(map);
            return resultObject;
        } catch (ExpiredJwtException e) {
            throw new MyException(StatusEnum.TOKEN_INVALID, "token失效");
        }
    }

    /**
     * 退出系统清理session
     *
     * @return
     */
    @PostMapping(value = "/sysExist", produces = MediaType.APPLICATION_JSON_VALUE)
    public void sysExist() {
        request.getSession().invalidate();
    }
}